using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.Search.Administration;

namespace Macaw.Moss2007.SearchEnhancements
{
    public class PublishingCrawlRulesFeatureReceiver : SPFeatureReceiver
    {

        private string[] rulepaths = new string[] { "*://*webfldr.aspx", "*://*mod-view.aspx*", "*://*my-sub.aspx*", "*://*allitems.aspx*", "*://*allforms.aspx*", "*://*/lists/*", "*://*DispForm.aspx*" };
        private void AddCrawlRule(Content content, string rulepath)
        {
            if (!content.CrawlRules.Exists(rulepath))
            {
                CrawlRule crawlrule = content.CrawlRules.Create(CrawlRuleType.ExclusionRule, rulepath);
                crawlrule.FollowComplexUrls = true;
                crawlrule.Update();
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;
            if (webapp.Sites.Count == 0) return;

            SearchContext searchcontext = SearchContext.GetContext(webapp.Sites[0]);
            if (searchcontext == null) return;

            Content content = new Content(searchcontext);

            foreach (string rulepath in rulepaths)
            {
                AddCrawlRule(content, rulepath);
            }

        }

        private void DeleteCrawlRule(Content content, string rulepath)
        {
            if (content.CrawlRules.Exists(rulepath))
            {
                CrawlRule crawlrule = content.CrawlRules[rulepath];
                crawlrule.Delete();
            }
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;
            if (webapp.Sites.Count == 0) return;

            SearchContext searchcontext = SearchContext.GetContext(webapp.Sites[0]);
            if (searchcontext == null) return;

            Content content = new Content(searchcontext);

            foreach (string rulepath in rulepaths)
            {
                DeleteCrawlRule(content, rulepath);
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {

        }
    }
}
